﻿using NPOI.SS.Formula.Eval;
using NPOI.SS.Formula.Functions;
using NPOI.Util.Collections;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EasyCore.Excel
{
    public class EntitySheetMapper<TEntity> : SheetMapper<TEntity>
    {



        public EntitySheetMapper(ExcelMapper excelMapper,string sheetName) : base(excelMapper,sheetName)
        {


        }

        public override string GetRowCell(int rowIndex, TEntity obj, ColumnOption<TEntity> columnOption)
        {
            string val = string.Empty;
            if (columnOption.FormatColumnVal != null) val = columnOption.FormatColumnVal(rowIndex, obj);
            else {
                var type = typeof(TEntity);
                var properties = type.GetProperties();
                if (!string.IsNullOrWhiteSpace(columnOption.FieldName))
                {
                    foreach (var p in properties)
                    {
                        if (columnOption.FieldName.ToLower() == p.Name.ToLower())
                        {

                            val = p.GetValue(obj, null).ToString();
                            break;
                        }
                    }
                }
                else if (!string.IsNullOrWhiteSpace(columnOption.ColumnName)) 
                {
                    foreach (var p in properties)
                    {
                        if (columnOption.ColumnName.ToLower() == p.Name.ToLower())
                        {

                            val = p.GetValue(obj, null).ToString();
                            break;
                        }
                    }
                }
            }
            return val;
        }

        public override void Put(object data)
        {
            DataSources = data as IEnumerable<TEntity>;
            //当没有为数据源配置时，则以数据源为标准执行数据导出
            if (ColumnOptions == null || !ColumnOptions.Any())
            {
                if (ColumnOptions == null) ColumnOptions = new List<ColumnOption<TEntity>>();
                ColumnOption<TEntity> temp = new ColumnOption<TEntity>();
                temp.ColumnType = ColumnType.MainIndex;
                temp.ColumnName = "序号";
                ColumnOptions.Add(temp);
                var type = typeof(TEntity);
                var properties = type.GetProperties();
                foreach (var p in properties)
                {
                    temp = new ColumnOption<TEntity>();
                    temp.ColumnName = p.Name;
                    temp.FieldName = p.Name;
                    ColumnOptions.Add(temp);
                }
            }
        }

    }
}
